<template>
  <div class="inputNumber">
    <button class="icon" @click="count(-1)" :disabled="props.num <= min">
      -
    </button>
    <input type="text" class="input" v-model="props.num" />
    <button class="icon" @click="count(1)" :disabled="props.num >= max">
      +
    </button>
  </div>
</template>

<script lang="ts">
export default {
  name: "inputNumber",
};
</script>

<script lang="ts" setup>
import { useShoppingCartStore } from "../../store/shoppingCart";
import { useAppStore } from "../../store/user";
import { updateShoppingCartApi } from "../../api/shopping";
import { ref } from "vue";
const props = defineProps(["productID", "num"]);
const shoppingCartStore = useShoppingCartStore();
const appStore = useAppStore();
const max = ref(5);
const min = ref(1);

const count = async (Num: any) => {
  // 定义请求参数
  const data = {
    user_id: appStore.user_id,
    product_id: props.productID,
    num: props.num + Num,
  };
  // 更改pinia购物车数量
  shoppingCartStore.shoppingCartData.map((item) => {
    if (item.productID === props.productID) {
      item.num = data.num;
    }
  });
  // 发起更新服务器请求
  await updateShoppingCartApi(data);
};
</script>

<style scoped>
.inputNumber {
  line-height: 38px;
  height: 38px;

  border: 1px solid #b0b0b0;
}
.icon {
  width: 100%;
  height: 100%;
  font-size: 20px;
  font-weight: 700;
}
.icon:hover {
  background-color: #ddd;
}
.input {
  width: 72px;
  height: 100%;
  outline: none;
  padding-left: 27px;
  color: #454545;
}
.input:active {
  border: none;
}
</style>
